#include "windowmanager.h"
#include "playermanager.h"
#include <QLayout>

QList<QWidget *> WindowManager::queue;
QPushButton * WindowManager::homeButton;
QPushButton * WindowManager::backButton;
QWidget * WindowManager::centralWidget;


WindowManager::WindowManager(QWidget * mainWidget,QPushButton * home, QPushButton * back)
{
    centralWidget=mainWidget;
    homeButton=home;
    backButton=back;
}

void WindowManager::goBack() {
    if(queue.size()>1) {
       queue.last()->hide(); //make sure it hides first

        queue.removeLast();
    }
    //size may decreases in the previous section
    if(queue.size()<=1){
        homeButton->setEnabled(false);
        backButton->setEnabled(false);
    }
    queue.last()->show();
    queue.last()->grabKeyboard();
}

void WindowManager::goHome() {
    while(1<queue.size()) {
        queue.last()->hide();
        queue.removeLast();
    }
    homeButton->setEnabled(false);
    backButton->setEnabled(false);
    queue.last()->show();
    queue.last()->grabKeyboard();
}

void WindowManager::goToNowPlaying() {

    if(PlayerManager::getCurrentPlayer()) {
        QWidget * player =PlayerManager::getCurrentPlayer();
        if(player==queue.last()) {
            return;
        }
        foreach(QWidget * widget,queue) {
            widget->hide();
        }
        showWidget(player);
    }
}

void WindowManager::showWidget(QWidget *widget) {
    if(queue.size()==0||queue.last()!=widget) {
        if(queue.size()>0) {
            queue.last()->hide();
            queue.last()->releaseKeyboard();
        }
        queue.append(widget);
        widget->show();
        widget->grabKeyboard();
        //QTimer::singleShot(0,widget,SLOT(show()));
    }
    if(queue.size()>1) {
        homeButton->setEnabled(true);
        backButton->setEnabled(true);
    }
}

void WindowManager::addWidget(QWidget *widget) {

    QLayout * layout=centralWidget->layout();
    widget->setParent(centralWidget);
    layout->addWidget(widget);
    widget->hide();
}

QWidget * WindowManager::getCurrent() {
    return queue.last();
}

void WindowManager::setHomeButton(QPushButton *button) {
    homeButton = button;
}

void WindowManager::setBackButton(QPushButton *button) {
    backButton = button;
}


